﻿namespace ECommerce.Controls
{
	using System;
	using System.Linq;
	using Data.Entity;
	using System.Collections.Generic;
	using System.Web.UI.WebControls;
	using Service;

	public partial class ProductsByCategory : BaseUserControl
	{
		private IProductService _ProductService;
		private IShoppingCartItemService _ShoppingCartItemService;
		private ICategoryService _CategoryService;
		private IEnumerable<Product> _DataSource;
		private int _TotalRecords;

		public string SearchKeyword
		{
			get
			{
				return CommonHelper.QueryString("searchkeyword");
			}
		}

		public int CategoryID
		{
			get
			{
				return CommonHelper.QueryStringInt("categoryid");
			}
		}

		public int RecommendedProducts
		{
			get
			{
				return CommonHelper.QueryStringInt("recommendproducts");
			}
		}

		public IEnumerable<Product> DataSource
		{
			get
			{
				var pageIndex = this.PageIndex;
				var totalRecords = 0;
				var pageSize = this.PageSize;

				if (CategoryID > 0)
				{
					if (_ProductService == null)
					{
						_ProductService = new ProductService();
					}

					if (string.IsNullOrEmpty(SearchKeyword))
					{
						_DataSource = _ProductService.GetProductsByCategory(CategoryID, pageIndex, pageSize, out totalRecords);

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
					else
					{
						_DataSource = _ProductService.GetProductsByCategory(CategoryID);

						if (_DataSource != null)
						{
							_DataSource = _DataSource.Where(p => p.MetaKeywords.Contains(SearchKeyword) || p.MetaTitle.Contains(SearchKeyword) ||
								p.Name.Contains(SearchKeyword) || p.ShortDescription.Contains(SearchKeyword));

							if (_DataSource != null)
							{
								totalRecords = _DataSource.Count();
								_DataSource = _DataSource.Skip(pageIndex * pageSize).Take(pageSize);
							}
							else
							{
								totalRecords = 0;
							}
						}

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
				}
				else
				{
					if (SiteContext.Current.WorkingLanguage == null)
					{
						this.TotalRecords = 0;
						return null;
					}

					int currentLanguageID = SiteContext.Current.WorkingLanguage.LanguageId;

					this.Page.Title = GetLocalResourceString("Ecommerce.PageTitle.Products");

					if (_ProductService == null)
					{
						_ProductService = new ProductService();
					}

					if (string.IsNullOrEmpty(SearchKeyword))
					{
						if (RecommendedProducts == 1)
						{
							this.Page.Title = GetLocalResourceString("Ecommerce.PageTitle.RecommendProducts");

							_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID, pageIndex, pageSize, out totalRecords);

							if (_DataSource != null)
							{
								if (_DataSource != null)
								{
									totalRecords = _DataSource.Count();
									_DataSource = _DataSource.Where(exp => exp.Recommend == true);
								}
								else
								{
									totalRecords = 0;
								}
							}

							this.TotalRecords = totalRecords;

							return _DataSource;
						}
						else
						{
							_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID, pageIndex, pageSize, out totalRecords);

							this.TotalRecords = totalRecords;

							return _DataSource;
						}
					}
					else
					{
						_DataSource = _ProductService.GetProductsByLanguage(currentLanguageID);

						if (_DataSource != null)
						{
							_DataSource = _DataSource.Where(p => p.MetaKeywords.Contains(SearchKeyword) || p.MetaTitle.Contains(SearchKeyword) ||
										p.Name.Contains(SearchKeyword) || p.ShortDescription.Contains(SearchKeyword));

							if (_DataSource != null)
							{
								totalRecords = _DataSource.Count();
								_DataSource = _DataSource.Skip(pageSize * pageIndex).Take(pageSize);
							}
							else
							{
								totalRecords = 0;
							}
						}

						this.TotalRecords = totalRecords;

						return _DataSource;
					}
				}
			}
		}

		public int PageIndex
		{
			get
			{
				if (ViewState["PageIndex"] == null)
				{
					return 0;
				}
				else
				{
					return int.Parse(ViewState["PageIndex"].ToString());
				}
			}
			set
			{
				ViewState["PageIndex"] = value;
			}
		}

		public int TotalRecords
		{
			get
			{
				return _TotalRecords;
			}
			set
			{
				_TotalRecords = value;
			}
		}

		public int TotalPages
		{
			get
			{
				var data = DataSource;

				if (data == null)
				{
					return 0;
				}

				int totalRecords = TotalRecords;

				int totalPages = 0;

				if (totalRecords <= PageSize)
				{
					totalPages = 1;
				}

				if (totalRecords % PageSize == 0)
				{
					totalPages = totalRecords / PageSize;
				}

				if (totalRecords % PageSize > 0)
				{
					totalPages = totalRecords / PageSize + 1;
				}

				return totalPages;
			}
		}

		public int PageSize
		{
			get
			{
				return this.GridProducts.PageSize;
			}
			set
			{
				this.GridProducts.PageSize = value;
			}
		}

		public string GetItemUrl(string prodID)
		{
			if (string.IsNullOrEmpty(prodID))
			{
				return "~/ProductDetail.aspx";
			}

			return string.Format("~/ProductDetail.aspx?productid={0}", prodID);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

		}

		protected void GridProducts_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/Login.aspx");
			}

			if (e.CommandName.Equals("AddToCart"))
			{
				var user = SiteContext.Current.User;

				if (user == null)
				{
					Server.Transfer("~/Login.aspx");
				}

				if (_ShoppingCartItemService == null)
				{
					_ShoppingCartItemService = new ShoppingCartItemService();
				}
				ShoppingCartItem theNewCart = new ShoppingCartItem();

				theNewCart.CreatedOn = DateTime.Now;
				theNewCart.ProductID = int.Parse(e.CommandArgument.ToString());
				theNewCart.Quantity = 1;
				theNewCart.ShoppingCartTypeID = (int)ShoppingCartType_Const.ShoppingCart;
				theNewCart.UpdatedOn = DateTime.Now;
				theNewCart.UserID = new Guid(user.ProviderUserKey.ToString());

				_ShoppingCartItemService.CreateNewShoppingCartItem(theNewCart);
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			this.LinkButtonFirstPage.Text = GetLocalResourceString("ProductList.LinkButtonFirstPageText");
			this.LinkButtonLastPage.Text = GetLocalResourceString("ProductList.LinkButtonLastPageText");
			this.LinkButtonNextPage.Text = GetLocalResourceString("ProductList.LinkButtonNextPageText");
			this.LinkButtonPrePage.Text = GetLocalResourceString("ProductList.LinkButtonPrePageText");
			this.LinkButtonFirstPage1.Text = GetLocalResourceString("ProductList.LinkButtonFirstPageText");
			this.LinkButtonLastPage1.Text = GetLocalResourceString("ProductList.LinkButtonLastPageText");
			this.LinkButtonNextPage1.Text = GetLocalResourceString("ProductList.LinkButtonNextPageText");
			this.LinkButtonPrePage1.Text = GetLocalResourceString("ProductList.LinkButtonPrePageText");
			this.LSortBySelectorLabel.Text = GetLocalResourceString("ProductList.SortBySelectorLabel");
			this.LTotalRecordsLabel.Text = GetLocalResourceString("ProductList.TotalRecordsLabel");
			this.LTotalPagesLabel.Text = GetLocalResourceString("ProductList.TotalPagesLabel");
			this.LTotalRecordsLabel1.Text = GetLocalResourceString("ProductList.TotalRecordsLabel");
			this.LTotalPagesLabel1.Text = GetLocalResourceString("ProductList.TotalPagesLabel");

			//if (!IsPostBack)
			//{
			BindCategoryNavPath();

			BindSortItems();

			BindProducts();
			//}

			var currentPageIndex = this.PageIndex;
			var totalPages = TotalPages;

			if (currentPageIndex == 0 || PageSize <= 1)
			{
				LinkButtonPrePage.Enabled = false;
				LinkButtonFirstPage.Enabled = false;
				LinkButtonPrePage1.Enabled = false;
				LinkButtonFirstPage1.Enabled = false;
			}
			else
			{
				LinkButtonPrePage.Enabled = true;
				LinkButtonFirstPage.Enabled = true;
				LinkButtonPrePage1.Enabled = true;
				LinkButtonFirstPage1.Enabled = true;
			}

			if (currentPageIndex == totalPages - 1 || totalPages <= 1)
			{
				LinkButtonLastPage.Enabled = false;
				LinkButtonNextPage.Enabled = false;
				LinkButtonLastPage1.Enabled = false;
				LinkButtonNextPage1.Enabled = false;
			}
			else
			{
				LinkButtonLastPage.Enabled = true;
				LinkButtonNextPage.Enabled = true;
				LinkButtonLastPage1.Enabled = true;
				LinkButtonNextPage1.Enabled = true;
			}

			// set pager index links
			List<PagerIndex> indexs = new List<PagerIndex>();

			if (totalPages <= 10)
			{
				for (int i = 1; i <= totalPages; i++)
				{
					indexs.Add(new PagerIndex(i.ToString()));
				}
			}
			else if (totalPages > 10)
			{
				if (((currentPageIndex / 10) * 10 + 10) > totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= totalPages; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
				else if (((currentPageIndex / 10) * 10 + 10) <= totalPages)
				{
					for (int i = (currentPageIndex / 10) * 10 + 1; i <= (currentPageIndex / 10) * 10 + 10; i++)
					{
						indexs.Add(new PagerIndex(i.ToString()));
					}
				}
			}

			this.RepeaterPageIndex.DataSource = indexs;
			this.RepeaterPageIndex.DataBind();
			this.RepeaterPageIndex1.DataSource = indexs;
			this.RepeaterPageIndex1.DataBind();

			this.LabelTotalPages.Text = totalPages.ToString();
			this.LabelTotalRecords.Text = TotalRecords.ToString();
			this.LabelTotalPages1.Text = totalPages.ToString();
			this.LabelTotalRecords1.Text = TotalRecords.ToString();

			// disenabel the current pagerindex link
			if (RepeaterPageIndex.TemplateControl.Controls.Count > 1)
			{
				for (int i = 0; i < RepeaterPageIndex.Items.Count; i++)
				{
					LinkButton thePagerIndexLink = RepeaterPageIndex.Items[i].FindControl("LinkButtonPageIndex") as LinkButton;

					if (thePagerIndexLink.Text.Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink.Enabled = false;
					}
				}

				for (int i = 0; i < RepeaterPageIndex1.Items.Count; i++)
				{
					LinkButton thePagerIndexLink1 = RepeaterPageIndex1.Items[i].FindControl("LinkButtonPageIndex1") as LinkButton;

					if (thePagerIndexLink1.Text.Equals((currentPageIndex + 1).ToString()))
					{
						thePagerIndexLink1.Enabled = false;
					}
				}
			}
		}

		private void BindCategoryNavPath()
		{
			if (_CategoryService == null)
			{
				_CategoryService = new CategoryService();
			}
			var currentCategory = _CategoryService.GetCategoryByID(CategoryID);

			if (currentCategory != null)
			{
				CategoryNavPath.InnerHtml = string.Empty;

				CategoryNavPath.InnerHtml += @"<a href='HomePage.aspx'>" +
											GetLocalResourceString("MenuItem.Home") + "</a>" +
											"<img width='12' style='vertical-align:bottom;margin-left:4px;margin-right:4px;' border='0' height='12' src='../App_Themes/Default/images/arrow.gif' />";

				var pageTitle = currentCategory.CategoryName;

				if (currentCategory.ParentCategoryID <= 0)
				{
					CategoryNavPath.InnerHtml += currentCategory.CategoryName;
				}
				else
				{
					var parentCategory = _CategoryService.GetCategoryByID(currentCategory.ParentCategoryID);

					CategoryNavPath.InnerHtml += @"<a href='Category.aspx?categoryid=" + parentCategory.CategoryID.ToString() + "'>" + parentCategory.CategoryName + "</a>";
					CategoryNavPath.InnerHtml += @"<img width='12' style='vertical-align:bottom;margin-left:4px;margin-right:4px;' border='0' height='12' src='../App_Themes/Default/images/arrow.gif' />" + currentCategory.CategoryName;

					pageTitle = parentCategory.CategoryName + "-" + pageTitle;
				}

				this.Page.Title = LocalizationManager.GetLocalResourceString("ECommerce.SiteName") + "-" + pageTitle;
			}
		}

		private void BindSortItems()
		{
			if (DropDownList_SortBy.Items == null || DropDownList_SortBy.Items.Count == 0)
			{
				this.DropDownList_SortBy.Items.Add(new ListItem(LocalizationManager.GetLocalResourceString("ProductList.SortByCreateTime"), "1"));
				this.DropDownList_SortBy.Items.Add(new ListItem(LocalizationManager.GetLocalResourceString("ProductList.SortByPriceAsc"), "2"));
				this.DropDownList_SortBy.Items.Add(new ListItem(LocalizationManager.GetLocalResourceString("ProductList.SortByPriceDesc"), "3"));
			}

		}

		private void BindProducts()
		{
			string selectedItem = this.DropDownList_SortBy.SelectedValue.Trim();

			if (selectedItem == "1")
			{
				//var data = DataSource.OrderByDescending(k => k.CreatedOn).Skip(PageSize * (PageIndex)).Take(PageSize);
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderByDescending(exp => exp.CreatedOn);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}

			if (selectedItem == "2")
			{
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderBy(exp => exp.ListPrice);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}

			if (selectedItem == "3")
			{
				var data = DataSource;

				if (data != null)
				{
					data = data.OrderByDescending(exp => exp.ListPrice);
				}

				GridProducts.DataSource = data;
				GridProducts.DataBind();
			}
		}

		/// <summary>
		/// paging event handler
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void LinkButtonPaging_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "FirstPage":
					{
						PageIndex = 0;

						//TotalRecords = DataSource.Count();

						//BindProducts();
					}
					break;
				case "PrePage":
					{
						if (PageIndex > 0)
						{
							PageIndex -= 1;
						}

						//TotalRecords = DataSource.Count();

						//BindProducts();
					}
					break;
				case "PageIndex":
					{
						LinkButton theLink = sender as LinkButton;

						int index = int.Parse(theLink.Text);

						PageIndex = index - 1;

						//TotalRecords = DataSource.Count();

						//BindProducts();
					}
					break;
				case "NextPage":
					{
						if (PageIndex < TotalPages)
						{
							PageIndex += 1;
						}

						//BindProducts();
					}
					break;
				case "LastPage":
					{
						PageIndex = TotalPages - 1;

						//TotalRecords = DataSource.Count();

						//BindProducts();
					}
					break;
			}
		}

		protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
		{
			//BindProducts();
		}

		protected void GridProducts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Separator)
			{
				HyperLink lk = (HyperLink)e.Row.FindControl("HyperLink1");

				if (lk != null)
				{
					lk.NavigateUrl = "~/ProductDetail.aspx?productid=" + ((Product)e.Row.DataItem).ProductID.ToString();
				}

			}
		}
	}
}